import action as action
from flask import render_template, session, jsonify, current_app, g
from flask import request
# 测试
from info import constants, db
from info.constants import CLICK_RANK_MAX_NEWS
from info.modules.news import news_blu
from info.models import User, News, Category, Comment, CommentLike
from info.response_code import RET
from info.utils.common import user_login_data


@news_blu.route('/<int:news_id>')
@user_login_data
def news_detail(news_id):
    user = g.user
    news_list = News.query.order_by(News.clicks.desc()).limit(CLICK_RANK_MAX_NEWS)
    click_news_list = []
    for news in news_list if news_list else []:
        click_news_list.append(news.to_dict())

    news = News.query.get(news_id)
    categories = Category.query.all()
    if not categories:
        return jsonify(errno=RET.NODATA, errmsg="数据不存在！")
    news.clicks += 1
    is_colleced=False
    comments = []
    comments = Comment.query.filter(Comment.news_id == news.id).order_by(Comment.create_time.desc()).all()
    comment_dict_li = []
    if user:
        if  news in user.collection_news:
            is_colleced=True
        user_comment_likes = CommentLike.query.filter(CommentLike.user_id == user.id).all()
        user_comment_ids = [comment_like.comment_id for comment_like in user_comment_likes]
        for comment in comments if comments else [] :
            comment_dict = comment.to_dict()
            comment_dict['is_like'] = False
            if comment.id in user_comment_ids:
                comment_dict["is_like"] = True
            comment_dict_li.append(comment_dict)
    data = {
        'user': user.to_dict() if user else None,
        "news_dict_list": news_list,
        "category_list":categories,
        "news":news.to_dict(),
        "is_collected":is_colleced,
        "comments": comment_dict_li,
        # "is_followed":is_followed,
    }
    return render_template('news/detail.html', data=data)
@news_blu.route("/news_collect", methods=['POST'])
@user_login_data
def news_collect():
    """新闻收藏"""
    # 获取参数
    # 判断参数
	# action在不在指定的两个值：'collect', 'cancel_collect'内
    # 查询新闻,并判断新闻是否存在
    # 收藏/取消收藏
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='请先登录')
    news_id = request.json.get('news_id')
    action = request.json.get('action')
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg='请输入参数')
    news = News.query.get(news_id)
    if action == 'collect':
        if news not in user.collection_news:
            user.collection_news.append(news)
        else:
            return jsonify(errno=RET.PARAMERR, errmsg='已经收藏过了')
    else:
        if news in user.collection_news:
            user.collection_news.remove(news)
        else:
            return jsonify(errno=RET.PARAMERR, errmsg='已经取消收藏过了')
    db.session.commit()
    return jsonify(errno=RET.OK, errmsg='OK')


@news_blu.route('/news_comment', methods=["POST"])
@user_login_data
def add_news_comment():
    """添加评论"""

    # 用户是否登陆
    user=g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR,errmsg="输入参数")
    # 获取参数
    news_id = request.json.get('news_id')
    news_comment=request.json.get("comment")
    print(news_id)
    print(news_comment)
    parent_id = request.json.get('parent_id')
    # 判断参数是否正确
    # 查询新闻是否存在并校验
    if not all([news_id,news_comment]):
        return jsonify(errno=RET.SESSIONERR,errmsg="输入参数")
    # 初始化评论模型，保存数据
    comment=Comment()
    comment.user_id=user.id
    comment.news_id = news_id
    comment.content = news_comment
    if parent_id:
        comment.parent_id = parent_id
    db.session.add(comment)
    db.session.commit()

    return jsonify(errno=RET.OK, errmsg='OK', data=comment.to_dict())
    # 配置文件设置了自动提交,自动提交要在return返回结果以后才执行commit命令,如果有回复
    # 评论,先拿到回复评论id,在手动commit,否则无法获取回复评论内容
    # 返回响应
@news_blu.route('/comment_like', methods=["POST"])
@user_login_data
def comment_like():
    """
    评论点赞
    :return:
    """
    # 用户是否登陆
    user=g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='请先登录')
    # 取到请求参数
    comment_id=request.json.get("comment_id")
    action = request.json.get("action")
    # 判断参数
    if not all([comment_id,action]):
        return jsonify(errno=RET.PARAMERR, errmsg='请输入参数')
    # 获取到要被点赞的评论模型
    comment = Comment.query.get(comment_id)
    commentLike_obj = CommentLike.query.filter(CommentLike.comment_id == comment_id,
                                               CommentLike.user_id == user.id).first()
    if action == 'add':
        if not commentLike_obj:
            comment_like = CommentLike()
            comment_like.comment_id = comment_id
            comment_like.user_id = user.id
            db.session.add(comment_like)
            comment.like_count += 1
    else:
        if commentLike_obj:
            db.session.delete(commentLike_obj)
            comment.like_count -= 1
    db.session.commit()
    return jsonify(errno=RET.OK, errmsg='OK')
	# action的状态,如果点赞,则查询后将用户id和评论id添加到数据库
            # 点赞评论
            # 更新点赞次数

        # 取消点赞评论,查询数据库,如果以点赞,则删除点赞信息

            # 更新点赞次数

	# 返回结果